package org.amphiprion.descentv2assistant.dao.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.amphiprion.descentv2assistant.App;
import org.amphiprion.descentv2assistant.ApplicationConstants;
import org.amphiprion.descentv2assistant.entity.Archetype;
import org.amphiprion.descentv2assistant.util.PreferenceUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.os.Environment;
import android.util.Log;

public class ArchetypeXmlDao extends AbstractXmlDao {
	private static ArchetypeXmlDao instance;

	public static ArchetypeXmlDao getInstance() {
		if (instance == null) {
			instance = new ArchetypeXmlDao();
		}
		return instance;
	}

	public List<Archetype> getArchetypes() {
		if (App.archetypes != null) {
			return App.archetypes;
		}
		List<Archetype> result = new ArrayList<Archetype>();
		String lng = PreferenceUtil.getLanguage();
		InputStream is = null;
		try {
			File f = new File(Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY + "/archetypes.xml");

			if (f.exists()) {
				is = new FileInputStream(f);
			}
			if (is == null) {
				is = App.class.getResourceAsStream("/archetypes.xml");
			}

			DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
			builderFactory.setNamespaceAware(true);

			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			Document document = builder.parse(is);

			NodeList list = document.getElementsByTagName("archetype");
			for (int i = 0; i < list.getLength(); i++) {
				Element archetypeNode = (Element) list.item(i);
				String id = archetypeNode.getAttributes().getNamedItem("id").getNodeValue();

				// NAME
				Element localizedNode = (Element) archetypeNode.getElementsByTagName("name").item(0);
				String name = getLocalizedText(localizedNode, lng);

				Archetype archetype = new Archetype(id);
				archetype.setName(name);
				result.add(archetype);
			}
			is.close();
			Collections.sort(result);
			App.archetypes = result;
			return result;
		} catch (Throwable e) {
			Log.e(ApplicationConstants.PACKAGE, "", e);
			if (is != null) {
				try {
					is.close();
				} catch (Throwable ex) {
				}
			}
			return null;
		}
	}

	public Archetype getArchetype(String archetypeId) {
		List<Archetype> archs = getArchetypes();
		if (archs != null) {
			for (Archetype arch : archs) {
				if (arch.getId().equals(archetypeId)) {
					return arch;
				}
			}
		}

		Archetype arch = new Archetype(archetypeId);
		arch.setName(archetypeId + ": NOT FOUND");
		return arch;
	}
}
